<?php
namespace thinkless;

use util\Logger;
use PDOException;
use exception\FriendlyException;
use exception\SystemException;
use security\exception\UnAuthorizationException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Env;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
        FriendlyException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response {
        // 添加自定义异常处理机制
        if($e instanceof UnAuthorizationException) {
            return json([
                'message' => $e->getMessage()
            ], $e->getCode());
        }
        if($e instanceof FriendlyException) {
            return $this->json($e->getCode(), $e->getMessage());
        }

        if(Env::get('APP_DEBUG')) return parent::render($request, $e);

        $message = $e->getMessage();
        if(strpos($message, 'module not exists') === 0 || strpos($message, 'controller not exists') === 0) {
            Logger::error($e, "系统路由异常", 'error', "system");
            return $this->json(100, '系统路由异常');
        }

        if ($e instanceof SystemException) {
            Logger::error($e, $e->getMessage(), $e->level, $e->businessCode);
            return $this->json($e->getCode(), $e->getMessage());
        }

        // 数据库链接失败
        if($e instanceof PDOException) {
            Logger::error($e, "数据库异常", 'fatal', "system");
            return $this->json(100, '数据获取失败');
        }

        if($e instanceof \think\Exception || $e instanceof \think\exception\HttpException){
            // $message = $e->getMessage();
            // if(strpos($message,'module not exists') != false || strpos($message,'method not exists') != false)
            Logger::error($e, "系统异常", 'error', "system");
            return $this->json(100, '系统异常~');
        }

        if($e instanceof \Exception){
            $message = $e->getMessage() ?? '系统异常';
            Logger::error($e, $message, 'fatal', "system");
            return $this->json($e->getCode() || 101, $message);
        }
        
        if($e instanceof \Error) {
            $message = $e->getMessage() ?? '未知系统错误';
            Logger::error($e, $message, 'fatal', "system");
            return $this->json($e->getCode() || 102, $message);
        }

        Logger::error($e, "未知系统错误~", 'fatal', "system");
        // 其他错误交给系统处理
        return parent::render($request, $e);
    }

    public function json($code, $message) {
        return json([
            'code' => $code,
            'data' => [],
            'message' => $message,
        ]);
    }
}
